import { Component, Host, h, VNode, ComponentInterface, Prop, Event, EventEmitter, Watch, forceUpdate } from '@stencil/core';
import { IBzCalendarConfig } from './core/interface/ibz-calendar-config';
import { IBzCalendarWeekController } from './core/controller/ibz-calendar-week-controller';

/**
 * 日历组件
 *
 * @export
 * @class IBzCalendar
 */
@Component({
    tag: 'ibz-calendar',
    styleUrl: 'ibz-calendar.scss'
})
export class IBzCalendar implements ComponentInterface {

    /**
     * 基本配置
     *
     * @type {IBzCalendarConfig}
     * @memberof IBzCalendar
     */
    @Prop()
    public option: IBzCalendarConfig = {};

    /**
     * 配置参数变更
     *
     * @memberof IBzCalendar
     */
    @Watch('option')
    public watchOption(): void {
        if (this.option) {
            this.$c.setOption(this.option);
            this.tick();
        }
    }

    /**
     * 数据变更事件
     *
     * @type {EventEmitter}
     * @memberof IBzCalendar
     */
    @Event({ eventName: 'data-change' })
    public dataChange: EventEmitter;

    /**
     * 单项数据点击
     *
     * @type {EventEmitter}
     * @memberof IBzCalendar
     */
    @Event({ eventName: 'item-click' })
    public itemClick: EventEmitter;

    /**
     * 发送新建项
     *
     * @type {EventEmitter}
     * @memberof IBzCalendar
     */
    @Event({ eventName: 'new-item' })
    public newItem: EventEmitter;

    /**
     * 发送组件加载完毕事件
     *
     * @type {EventEmitter}
     * @memberof IBzCalendar
     */
    @Event({ eventName: 'did-load' })
    public didLoad: EventEmitter;

    /**
     * 日历「周」模式控制器
     *
     * @protected
     * @type {IBzCalendarWeekController}
     * @memberof IBizWeekView
     */
    protected $c: IBzCalendarWeekController = new IBzCalendarWeekController();

    /**
     * 日历数据
     *
     * @type {any[]}
     * @memberof IBzCalendar
     */
    @Prop()
    public items: any[] = [];

    /**
     * 组件加载之前
     *
     * @memberof IBzCalendar
     */
    public componentWillLoad(): void {
        this.$c.setOption(this.option);
        this.$c.setCalendar(this);
    }

    /**
     * 组件加载完毕
     *
     * @memberof IBzCalendar
     */
    public componentDidLoad(): void {
        setTimeout(() => this.didLoad.emit());
    }

    /**
     * 绘制日历
     *
     * @returns {VNode}
     * @memberof IBzCalendar
     */
    public render(): VNode {
        return (
            <Host class='ibz-calendar'>
                <ibz-week-view $c={this.$c} items={this.items}></ibz-week-view>
            </Host>
        );
    }

    /**
     * 强制脏检查
     *
     * @returns {Promise<void>}
     * @memberof IBzCalendar
     */
    public async tick(): Promise<void> {
        forceUpdate(this);
    }

}
